<?php

	/**
	* @author Robbie Vasquez
	* @author Matt Kennedy
 	* 
 	* @param username
	* @param distance
	* @param hours
	* @param minutes
	* @param seconds
	* @param month
	* @param day
	* @param year
	* @param routeID
	* @param comments
 	*/
	
class Addrun extends Model
{
	//creating variables
	var $username = '';
	var $distance = '';
	var $hours = '';
	var $minutes = '';
	var $seconds = '';
	var $month = '';
	var $day = '';
	var $year = '';
	var $routeID = '';
	var $comments = '';
	
	//creating function for add a run
	public function Addrun()
	{
		// Call the model constructor
		parent::Model();
		
		$this->load->database();
	}
	
	//creating function to record information
	public function record()
	{
		//creating array for errors
		$errors = array();
	
		if(isset($_POST) && $_POST != NULL)
		{
			//checking if a route is selected
			if($_POST['selectroute'] != '')
			{
				//connecting to database
				mysql_connect('2006.ispace.ci.fsu.edu', 'rmv06d', 'zqgvht2m');
				mysql_select_db('runningrecords');
						
				$sql = "SELECT * FROM routes WHERE username='" . $_SESSION['username'] . "'";
				$result = mysql_query($sql) or die(mysql_error());
				$pull = mysql_fetch_array($result) or die(mysql_error());
				
				$miles = $pull['miles'];
				$kilometers = $pull['kilometers'];
			}
			else
			{
				//checking if distance is a number, then converting it accordingly
				if(is_numeric($_POST['distance']))
				{
					//converint miles to kilometers
					if($_POST['unit'] == 'miles')
					{
						$miles = $_POST['distance'];
						$kilometers = $miles * 1.609;
						
						unset($_POST['distance']);
					}
					
					//converint kilometers to miles
					if($_POST['unit'] == 'kilometers')
					{
						$kilometers = $_POST['distance'];
						$miles = $kilometers / 1.609;
						
						unset($_POST['distance']);
					}
				}
				
				//checking if user entered a number if not, error message
				else
					$errors[] = "The distance must be numeric.";
			}
			
			//if there are no errors then continue forwarding information
			if(count($errors) < 1)
			{
				$run = array('username' => $_SESSION['username'], 'miles' => $miles, 'kilometers' => $kilometers, 'hours' => $_POST['hours'], 'minutes' => $_POST['minutes'], 'seconds' => $_POST['seconds'], 'month' => $_POST['month'], 'day' => $_POST['date'], 'year' => $_POST['year'], 'routeID' => $_POST['selectroute'], 'comments' => $_POST['comments']);
			
				$this->db->insert('runs', $run);
				header("Location: /runningrecords/index.php/listing/list_runs");
				die();
			}
			
			return $errors;
			
		}
	}
}